﻿using Castle.DynamicProxy;
using Fierce.Utility.Helper;
using System;
using System.Collections.Generic;
using System.Text;

namespace Fierce.Core.Aop
{
    /// <summary>
    /// 拦截器
    /// </summary>
    public class Interceptor : IInterceptor
    {
        private AopTarget _target;

        private void PreProceede() { _target.PreProceede(); }

        private void PostProceede() { _target.PostProceede(); }

        public void Intercept(IInvocation invocation)
        {
            _target = invocation.InvocationTarget as AopTarget;

            try
            {
                PreProceede(); invocation.Proceed();
            }
            catch (Exception ex)
            {
                LogHelper.Error(_target, ex, ex.Message);
            }
            finally { PostProceede(); }
        }

        internal static T CreateProxy<T>() where T : AopTarget, new()
        {
            ProxyGenerationOptions pgo = new ProxyGenerationOptions();

            pgo.Selector = new InterceptorSelector();
            pgo.Hook = new ProxyGenerationHook();

            return new ProxyGenerator().CreateClassProxy<T>(pgo, new Interceptor());
        }
    }
}